package com.lap.component.gateway.configure;

import com.lap.framework.common.constant.Header;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.client.ClientRequest;
import org.springframework.web.reactive.function.client.WebClient;

@Configuration
public class WebClientConfig {

  @Value("${auth.service.name}")
  private String authServiceName;

  @Bean
  @LoadBalanced
  WebClient.Builder loadBalancedWebClientBuilder() {
    return WebClient.builder();
  }

  @Bean
  WebClient authWebClient(WebClient.Builder builder) {
    return builder
        .baseUrl(authServiceName)
        .filter(
            (request, next) -> {
              String requestId = MDC.get(Header.REQUEST_ID);
              if (StringUtils.isNotBlank(requestId)) {
                ClientRequest newRequest =
                    ClientRequest.from(request).header(Header.REQUEST_ID, requestId).build();
                return next.exchange(newRequest);
              }
              return next.exchange(request);
            })
        .build();
  }
}
